/**
 * 
 */
package idv.takeshi.software.productline.bookstore.utils.text;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;
import org.apache.commons.lang.text.StrTokenizer;

/**
 * A utility for manipulating servlet path string.
 * @author takeshi
 *
 */
public class ServletPathStringUtils {
	
	private static final String QUESTION_MARK = "?";
	
	private static final String QUERY_STRING_DELIMITER = "&";
	
	/**
	 * Always not instantiate this utility.
	 */
	private ServletPathStringUtils(){}
	
	/**
	 * Get a new path which has specified query paramNames removed.
	 * @param servletPathAndQueryString
	 * @param paramNames
	 * @return
	 */
	public static String removeQueryStringParameters(String servletPathAndQueryString, String... paramNames){
		Validate.notEmpty(servletPathAndQueryString, "servletPathAndQueryString shall always not be null/empty");
		Validate.notEmpty(paramNames, "paramNames shall always not be null/empty");
		
		String queryString = null;
		StrTokenizer st = null; 
		StringBuffer newPath = new StringBuffer();
		
		if(StringUtils.indexOf(servletPathAndQueryString, QUESTION_MARK) == -1){
			newPath.append(servletPathAndQueryString);
		} else {
			queryString = StringUtils.substringAfter(servletPathAndQueryString, QUESTION_MARK);
			newPath.append(StringUtils.substringBefore(servletPathAndQueryString, QUESTION_MARK));
			
			st = new StrTokenizer(queryString);
			st.setDelimiterString(QUERY_STRING_DELIMITER);
			
			String token = null;
			int a = 0;
			StringBuffer newQueryString = new StringBuffer();
			while(st.hasNext()){
				token = null;
				if(a == 0){
					token = st.nextToken();
				} else{
					token = QUERY_STRING_DELIMITER + st.nextToken();
				}
				if(!matchParamNames(token, paramNames)){
					newQueryString.append(token);
					a++;
				}
			}
			
			if(newQueryString.length() > 0)
				newPath.append(QUESTION_MARK).append(newQueryString);
		}
		return newPath.toString();
	}
	
	private static boolean matchParamNames(String token, String[] paramNames){
		boolean match = false;
		
		for(String paramName : paramNames){
			if(StringUtils.indexOf(token, paramName) > -1){
				match = true;
				break;
			}
		}
		return match;
	}

}
